package com.net.core.core;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * RestTemplate的日志拦截器
 *
 * @author YuChangjiang
 */
@Slf4j
public class LoggingRestTemplateInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        this.traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        this.traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) {
        String requestInfo = "请求信息：" + "\n" +
                "uri：" + request.getURI() + "\n" +
                "method：" + request.getMethod() + "\n" +
                "headers：" + request.getHeaders() + "\n" +
                "request body：" + new String(body, StandardCharsets.UTF_8);
        log.debug(requestInfo);
    }

    private void traceResponse(ClientHttpResponse httpResponse) throws IOException {
        String responseInfo = "响应信息：" + "\n" +
                "status：" + httpResponse.getStatusCode() + "\n" +
                "headers：" + httpResponse.getHeaders() + "\n" +
                "response body：" + IoUtil.read(httpResponse.getBody(), StandardCharsets.UTF_8);
        log.debug(responseInfo);
    }
}
